/*
 * ex020104_forkafter.c
 */
#include <stdio.h>

#include <sys/types.h>
#include <unistd.h>

#include <errno.h>
#include <string.h>

typedef struct Info
{
	int pid;
	int seg;
}Info;

FILE *fp = NULL;
int segno = 0;

void OpenFile(char *path);
void CloseFile();
void ReadFile();
void WriteFile();

int main(int argc ,char *argv[])
{
	int pid = -1;

	pid = fork();
	if(pid == 0)
	{
		OpenFile("test");

		// in child 
		printf("here in child ,my pid is %d\n", getpid());

		WriteFile();
		sleep(5);

		WriteFile();
		sleep(5);
		
		WriteFile();
	}
	else if(pid > 0)
	{
		OpenFile("test");
		// in parent
		printf("here in parent, my pid %d, child pid is %d\n", getpid(), pid);

		sleep(3);
		ReadFile();

		sleep(5);
		ReadFile();

		sleep(5);
		ReadFile();
	}
	else
	{
		// error
		printf("fork error[%s]\n",strerror(errno));
	}

	CloseFile();
	return 0;
}

void OpenFile(char *path)
{
	if(NULL == path)
		return;

	fp = fopen(path, "w+");
	if(NULL == fp)
	{
		printf("open file %s error!\n", path);
	}

	return;
}

void CloseFile()
{
	if(NULL != fp)
		fclose(fp);
}

void ReadFile()
{
	Info rinfo = {0};
	int pos = 0;

	if(NULL == fp)
		return ;

	/* data read from current position record by the fp. */
	pos = ftell(fp);
	fread(&rinfo, sizeof(rinfo), 1, fp);	
	printf("[%d] read from %d, context(%d, %d) \n", getpid(), pos, rinfo.pid, rinfo.seg);
}

void WriteFile()
{
	Info winfo = {0};
	int pos = 0;

	if(NULL == fp)
		return ;

	winfo.seg = segno++;
	winfo.pid = getpid();

	/* data read from current position record by the fp. */
	pos = ftell(fp);
	fwrite(&winfo, sizeof(winfo), 1, fp);	
	fflush(fp);

	printf("[%d] write to %d, context(%d, %d) \n", getpid(), pos, winfo.pid, winfo.seg);
}
